require.config({
	baseUrl: document.getElementById("resDomain").href + "/scripts",
	paths: {
        js: './',
        com: '../common',
        jquery: './jquery-1.9.1.min',
        placeholder: './jquery.placeholder.min',
        qrcode: './jquery.qrcode-0.11.0.min',
        jwerty: './jwerty',
        bootstrap: './bootstrap-3.3.5/bootstrap.min',
        bootstrapswitch: './bootstrap-3.3.5/bootstrap-switch.min',
        ckfinder: '../common/module/ckfinder_2.3.1/ckfinder',
        region: './region',
        classify: './goodsClassify',
        category: './category',
        media: './html5media-1.1.8/html5media.min'
    }
});

define(["jquery"],function() {
	
	window.Common = (function() {
		return {};
	})();
	
	window.doing = function(bool) {
		if (bool === undefined) {
			return $(document).data("doing");
		}
		if (bool === false) {
			setTimeout(function() {
				$(document).data("doing", bool);
			},500);
		} else {
			$(document).data("doing", bool);
		}
		return bool;
	};

	Common.clearSessionStorage = function() {
		if (!sessionStorage) {
			return null;
		}
		sessionStorage.clear();
	};
	Common.setLocalStorage = function(key, data) {
		if (!localStorage) {
			return;
		}
		localStorage.setItem(key, data);
	};
	Common.getLocalStorage = function(key) {
		if (!localStorage) {
			return null;
		}
		return localStorage.getItem(key);
	};
	
	Common.referrer = function(defUrl, lazyTime) {
		$(document).showMsg("正在跳转...", 'pass');
		setTimeout(function() {
			if (document.referrer && document.referrer.indexOf("member/login") < 0) {
				location.href = document.referrer;
			} else {
				location.href = defUrl;
			}
		}, lazyTime !== undefined ? lazyTime : 2000);
	}
	
	Common.log = function(msg) {
		console ? console.log(msg) : void(0);
	}

	// 日期类扩展
	Date.prototype.format = function(fmt) { //author: meizz   
	  var o = {   
	    "M+" : this.getMonth()+1,                 //月份   
	    "d+" : this.getDate(),                    //日   
	    "h+" : this.getHours(),                   //小时   
	    "m+" : this.getMinutes(),                 //分   
	    "s+" : this.getSeconds(),                 //秒   
	    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
	    "S"  : this.getMilliseconds()             //毫秒   
	  };   
	  if(/(y+)/.test(fmt)) {
	  	fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));  
	  }  
	     
	  for(var k in o) {
	    if(new RegExp("("+ k +")").test(fmt))   {
	  		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
	    }
	  }
	  return fmt;   
	};
	Date.prototype.daysInMonth = function() {  
	     return new Date(this.getFullYear() + "/"+ (this.getMonth() + 1) +"/0").getDate();
	};
	Date.prototype.distance = function(date) {
		
		var startDate = this;
		var endDate = date;
		if (startDate.getTime() > date.getTime()) {
			startDate = date;
			endDate = this;
		}

		var startParts = startDate.format("yyyy_MM_dd_hh_mm").split(/_/);
		var endParts = endDate.format("yyyy_MM_dd_hh_mm").split(/_/);
		var distance = "";
		var subtractHour = 0;
		var subtractDay = 0;
		var subtractMonth = 0;
		if (parseInt(endParts[4]) > parseInt(startParts[4])) {
			distance = (parseInt(endParts[4]) - parseInt(startParts[4])).toFixed(0) + "分钟" + distance;
		} else if (parseInt(endParts[4]) < parseInt(startParts[4])) {
			distance = (60 - parseInt(startParts[4]) + parseInt(endParts[4])).toFixed(0) + "分钟" + distance;
			subtractHour = 1;
		}
		if (parseInt(endParts[3]) - subtractHour > parseInt(startParts[3])) {
			distance = (parseInt(endParts[3]) - subtractHour - parseInt(startParts[3])).toFixed(0) + "小时" + distance;
		} else if (parseInt(endParts[3]) < parseInt(startParts[3])) {
			distance = (24 - (parseInt(startParts[3]) - subtractHour) + parseInt(endParts[3])).toFixed(0) + "小时" + distance;
			subtractDay = 1;
		}
		if (parseInt(endParts[2]) - subtractDay > parseInt(startParts[2])) {
			distance = (parseInt(endParts[2]) - subtractDay - parseInt(startParts[2])).toFixed(0) + "天" + distance;
		} else if (parseInt(endParts[2]) < parseInt(startParts[2])) {
			distance = (startDate.daysInMonth() - (parseInt(startParts[2]) - subtractDay) + parseInt(endParts[2])).toFixed(0) + "天" + distance;
			subtractMonth = 1;
		}
		if (parseInt(endParts[1]) - subtractMonth > parseInt(startParts[1])) {
			distance = (parseInt(endParts[1]) - subtractMonth - parseInt(startParts[1])).toFixed(0) + "个月" + distance;
		} else if (parseInt(endParts[1]) - subtractMonth < parseInt(startParts[1])) {
			distance = (12 - (parseInt(startParts[1]) - subtractMonth) + parseInt(endParts[1])).toFixed(0) + "个月" + distance;
		}
		if (parseInt(endParts[0]) > parseInt(startParts[0])) {
			distance = (parseInt(endParts[0]) - parseInt(startParts[0])).toFixed(0) + "年" + distance;
		}
		return distance;
		
	};
	Date.prototype.name = function(){
		var date = this;
		var year = date.getFullYear();
		var mon = date.getMonth();
		var dat = date.getDate();
		var hour = date.getHours();
		var min = date.getMinutes();
		var sec = date.getSeconds();
		var curDate  = new Date();
		var curYear = curDate.getFullYear();
		var curMon = curDate.getMonth();
		var curDat = curDate.getDate();
		var curHour  = curDate.getHours();
		var curMin = curDate.getMinutes();
		var str = "";
		
		if(curYear-year ==0){
			if(curMon-mon >1){
				str +=(mon+1)+"月"+dat+"日";
			}
			else if(curMon-mon ==1){
				str +="上月"+dat+"日";
			}
			else{
				if(curDat-dat==0){
					str +="今天";
				}
				else if(curDat-dat==1){
					str +="昨天";
				}
				else if(curDat-dat==2){
					str +="前天";
				}
				else{
					str +=dat+"日";
				}
			}
		}
		else{
			if(curYear-year>2){
				str += year+"年";
			}
			else if(curYear-year ==2){
				str += "前年";
			}
			else if(curYear-year ==1){
				str += "去年";
			}
			
			str +=(mon+1)+"月"+dat+"日";
			
		}
		if(hour>18){
			str +="晚上"+(hour-12)+"点";
		}
		else if(hour>12){
			str +="下午"+(hour-12)+"点";
		}
		else if(hour==12){
			str +="中午"+hour+"点";
		}
		else if(hour>6){
			str +="上午"+hour+"点";
		}
		else{
			str +="零晨"+hour+"点";
		}
		if(min==30){
			str +="半";
		}
		else if(min==0){
			str +="整";
		}
		else{
			str +=min+"分";
		}
		return str;
	};
	
	
	// 域名变量
	(function() {
		var domainVars = "";
		$("link[rel='dns-prefetch']").each(function() {
			domainVars += "g_" + $(this).attr("id") + "='" + $(this).attr("href") + "';";
			eval("g_" + $(this).attr("id") + "='" + $(this).attr("href") + "';");
		});
		eval(domainVars);
	})();
	
	
	// 插件配置
	var plugins = {
		msgbox: {
			js:[
			    "com/js/msgbox/jquery.msgbox.min",
			    "com/js/msgbox/jquery.msgbox.i18n"
			   ],
			css:[
			     "/common/js/msgbox/themes/metro/css/jquery.msgbox.css"
			    ],
			callback: function() {
				$.msgbox.defaults({
					lang: "zh_CN",
					overlay: true,
					opacity: 0.1,
					resize: false
				});
			}
		},
		datepicker: {
			js:["com/js/datepicker/WdatePicker"],
			css:["/common/js/datepicker/skin/WdatePicker.css"]
		},
		pagectrl: {
			js:["com/js/pagectrl"],
			css:[]
		},
		fun: {
			js:["com/js/fun"],
			css:[]
		},
		region: {
			js:["js/region"],
			css:[]
		},
		category: {
			js:["js/category"],
			css:[]
		},
		goodsClassify: {
			js:["js/goodsClassify"],
			css:[]
		},
		validator: {
			js:[
			    "js/validator-0.7.3/jquery.validator",
			    "js/validator-0.7.3/local/zh_CN"
			   ],
			css:["/scripts/validator-0.7.3/jquery.validator.css"]
			
		},
		jwerty: {
			js:["js/jwerty"],
			css:[]
			
		},
		common: {
			js:[],
			css:["/css/my-com.css"]
		}
	};

	window.loadjs = function(names, callback) {
		var LOADING = "loading",LOADED = "loaded";
		var pluginNum = names.length;
		var len = pluginNum;
		for (var i = 0; i < len; i++) {
			loadPlugin_(names[i]);
		}
		
		function loadPlugin_(name) {
			var plugin = plugins[name];
			if (!plugin && console) {
				console?console.log("找不到插件:" + name):void(0);
				return;
			}
			if (plugin.status === LOADED) {
				pluginNum--;
				if (pluginNum <= 0) {
					callback?callback():void(0);
				}
				return;
			} else if (plugin.status === LOADING) {
				plugins[name].callback = (function(defCallback, appendCallback) {
					return function() {
						defCallback?defCallback():void(0);
						appendCallback?appendCallback():void(0);
					};
				})(plugins[name].callback, callback);
				return;
			}
			
			plugins[name].status = LOADING;
			
			var len = plugin.css.length;
			for (var j = 0; j< len; j++) {
				var cssPath = plugin.css[j];
				if (cssPath.indexOf("/") === 0 && g_resDomain) {
					cssPath = g_resDomain + cssPath;
				}
				$("head").append('<link href="' + cssPath + '" rel="stylesheet" type="text/css" />');
			}
			
			if (plugin.js.length > 0) {
				load_(plugin.js, 0);
			}
			
			function load_(jss, i) {
				require([jss[i]], function() {
					if (i < jss.length - 1) {
						load_(jss, i + 1);
						return;
					}
					plugins[name].status = LOADED;
					plugins[name].callback?plugins[name].callback():void(0);
					
					pluginNum--;
					if (pluginNum > 0) {
						return;
					}
					callback?callback():void(0);
					
				});
			}
		};
	};

	loadjs(["common"]);
	
	// 其它公共处理####################################################################################

	// 扩展属性
	$.extend($.fn,{
		its: function(attrValue) {
			return $(this).find("[its=" + attrValue + "]");
		}
	});

	// 扩展滚动事件
	$.extend($.fn,{
		scrollLoad: function(callback) {
			if (!callback) {
				load_();
				return $that;
			}
			var eventName = 'lazyWork';
			var $that = $(this);
			var isDoing = false;
			
			$(document).on(eventName, $that.selector, function() {
				var $target = $(this);
				var elHeight = $target.height();
				var elTop = $target.offset().top;
				var wHeight = $(window).height();
				var wScrollTop = $(window).scrollTop();
				if ((wScrollTop >= elTop && wScrollTop < (elTop + elHeight)) || (wScrollTop < elTop && (wScrollTop + wHeight) >= elTop) ) {
					callback($target);
				}
			});
			
			$(window).scroll(load_);
			$(window).scroll();
			
			function load_() {
				if (isDoing) return;

				isDoing = true;
				setTimeout((function(selector) {
					return function() {
						$(selector).each(function() {
							$(this).trigger(eventName);
						});
						isDoing = false;
					};

				})($that.selector));
			}
			return $that;
		}
	});
			
	//图片懒加载
	$("img[data][dtype!='tmp']").scrollLoad(function($el) {
		var src = $el.attr("data");
		if (src.indexOf("http") !== 0) {
			src = g_attaDomain + src;
		}
		$el.attr("src", src);
		$el.removeAttr("data");
	});
	
	//图片加载失败
	$("img").error(function() {
		$(this).attr("src", g_resDomain + "/images/goods_def.jpg");
	});

	$.extend($.fn,{
		showMsg: function(msg, type, lock) {
			var $this = $(this);
			if (!msg) {
				$this.trigger('hideMsg');
				setTimeout(function() {
					$this.data('locked', false);
				},1000);
				return true;
			}
			
			if (lock && $this.data('locked')) {
				return false;
			}
			
			if (lock) {
				$this.data('locked', true);
			} else {
				setTimeout(function() {
					$this.data('locked', false);
				},1000);
			}
			
			if ($this.data('hasMsg')) {
				$this.trigger('changeMsg', [msg, type]);
				return true;
			}
			$this.data('hasMsg', true);
			
			var $el = $('.myMsg');
			if ($el.length === 0) {
				$el = $("<div class='myMsg'></div>");
				$("body").prepend($el);
			}
			var $tip = $('<div style="margin-top:5px;"></div>');
			$el.append($tip);
			
			$this.on('changeMsg', function(event, msg, type) {
				$tip.attr('class', type);
				$tip.html(msg);
				if (type !== 'load') {
					$tip.stop(true,true).show().delay(2000).fadeOut(function() {$tip.hide();});
				} else {
					$tip.show();
				}
				return false;
			});
			$this.on('hideMsg', function() {
				$tip.fadeOut();
				return false;
			});
			
			$this.trigger('changeMsg', [msg, type]);
		
			return true;
		},
		doing: function(bool) {
			var $this = $(this);
			var preDoing = $this.data('locked');
			if (bool === undefined) {
				return preDoing;
			}
			if (bool === false) {
				setTimeout(function() {
					$this.removeData("locked");
				},1000);
			} else if (!preDoing) {
				$this.data("locked", bool);
			}
			return preDoing; 
		}
	});

	(function(){
		var timeIndex = -1;
		$.extend($.fn,{
			tip: function(msg, type, autoHide) {
				type=type?type:"ok";
				var $that = $(this);
				clearTimeout(timeIndex);
				$that.addClass("msg-box linealMsg").show();
				$that.html('<span class="msg-wrap n-' + type + '" role="alert"><span class="n-icon"></span><span class="n-msg">' + msg + '</span></span>');
				if (autoHide) {
					timeIndex = setTimeout(function() {
						$that.fadeOut();
					}, autoHide > 0 ? autoHide : 2000);
				}
				return $that;
			}
		});
	})();
	
	// (ie兼容plascholder)
	require(["placeholder"], function() {
		// (ie兼容plascholder)
		$("input,textarea").placeholder();
		// (ie兼容autofocus)
		$("[autofocus]").focus().select();
	});
	
	
	// 订单通知
	(function() {
		
		var $target = $("<div>");
		var intervalIndex = -1;
		
		// 非子窗口并且已经开启订单通知
		if (!window.opener && Common.getLocalStorage("isShowNewOrderTip") !== "false") {
			start_();
		} 
		
		// 查看订单
		$(document).on('click', "#seeNewOrder", function() {
			location.href = g_shopDomain + "/order/list?statuses=0,2";
		});
		
		// 音乐开关切换
		$(document).on('click', "#oss", function() {
			// 将开关状态保存在本地缓存
			Common.setLocalStorage("isPlayNewOrderAudio", Common.getLocalStorage("isPlayNewOrderAudio") !== "false" ? "false" : "true");
			$(document).trigger('newOrderAudioSwitch.change');
		});
		
		$(document).on('newOrderTipSwitch.change', function() {
			$target.doing(false);
			stop_();
			if (Common.getLocalStorage("isShowNewOrderTip") === "false") {
				$target.showMsg();
			} else {
				start_();
			}
		});
		
		$(document).on('newOrderAudioSwitch.change', function() {
			if (Common.getLocalStorage("isPlayNewOrderAudio") === "false") {
				$("#oss").addClass("voloff");
				stop_();
			} else {
				$("#oss").removeClass("voloff");
				if ($("#oss").length > 0 && !playing_()) {
					play_();
				}
			}
		});
		
		function start_() {
			loadStatus_();
			clearInterval(intervalIndex);
			intervalIndex = setInterval(loadStatus_, 30000);
		}
		
		function loadStatus_() {
			if ($target.doing()) {
				clearInterval(intervalIndex);
				return;
			}
			$.get(g_domain + "/common/orderTip/json?=r" + Math.random(), function(data) {
				if (data.status != 0) {
					clearInterval(intervalIndex);
					return;
				}
				// data.result -> isNewOrder (boolean)
				if (!data.result && $target.doing()) {
					
					$target.showMsg();
					stop_();
					
				} else if (data.result && !$target.doing()) {
					
					var vol = "voloff";// style class name
					
					// 从本地缓存中获得播放开关状态
					if (Common.getLocalStorage("isPlayNewOrderAudio") !== "false") {
						play_();
						vol = "";
					}
					
					// oss -> orderSoundSwitch
					$target.showMsg("<a id='oss' class='voldef " + vol + "'></a><a id='seeNewOrder' class='newmsg'>有新订单！</a>", 'load', true);
				}
				
			});
		}
		
		function play_() {

			var source = g_resDomain + "/images/new_order";
			$("body").append("<audio id='orderAudio' autoplay loop class='simulatehide'> <source src='" + source + ".mp3'></source> <source src='" + source + ".ogg'></source></audio>");
			require(["media"], function() {
				html5media();
			});
		}
		
		function stop_() {
			$("#orderAudio").remove();
		}
		
		function playing_() {
			return $("#orderAudio").length > 0;
		}
	})();
	
	//公共表单样式
	  $(".fill p").addClass("f_clear");
	  $(".form input[type=text],.form input[type=password],.form textarea").addClass("k");
	  $(".form input[type=radio]").addClass("radio");
	  $(document).on("focus", ".form input[type=text],.form input[type=password],.form textarea", function() {
		  $(this).addClass("hover");
		  $(this).addClass("selected");
	  }).on("blur", ".form input[type=text],.form input[type=password],.form textarea", function() {
		  $(this).removeClass("hover");
		  $(this).removeClass("selected");
	  });
	  $(document).on("focus", ".form select", function() {
		  $(this).addClass("selected");
	  }).on("blur", ".form select", function() {
		  $(this).removeClass("selected");
	  });
	 //
});

